package com.kkwrite.regimen.provider.stream.service;

import com.kkwrite.regimen.provider.service.point.PointService;
import com.kkwrite.regimen.provider.stream.StreamInputAndOutput;
import com.kkwrite.regimen.provider.stream.dto.RewardPointDTO;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * Created by Ron on 2018/9/28 9:46.
 *
 * @author Ron
 */
@Service
public class RewardPointService {

    @Resource
    private StreamInputAndOutput streamInputAndOutput;
    @Resource(name = "pointService")
    private PointService pointService;

    public boolean send(RewardPointDTO rewardPointDTO) {
        Assert.notNull(rewardPointDTO, "入参不能为null");
        return streamInputAndOutput.rewardPointOutput().send(MessageBuilder.withPayload(rewardPointDTO).build());
    }

    @StreamListener(StreamInputAndOutput.REWARD_POINTS_IN_CHANNEL)
    public void handler(RewardPointDTO rewardPointDTO) {
        if (rewardPointDTO == null) {
            return;
        }
        if (rewardPointDTO.getType() != null) {
            pointService.addSharePointRecord(rewardPointDTO.getUserId(), rewardPointDTO.getValue(),
                    rewardPointDTO.getSource(), rewardPointDTO.getType(), rewardPointDTO.getItemId());
        } else {
            pointService.addPointRecord(rewardPointDTO.getUserId(), rewardPointDTO.getValue(), rewardPointDTO.getSource());
        }
    }

}
